package com.trkj.service;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * 考勤管理服务层
 * @author 吴山峰
 *
 */

import com.trkj.dao.AttendanceDAO;
import com.trkj.dao.AttendanceparamDAO;
import com.trkj.dao.AttendancetypeDAO;
import com.trkj.dao.DeptDAO;
import com.trkj.dao.EmpDAO;
import com.trkj.pojo.Attendance;
import com.trkj.pojo.Attendanceparam;
import com.trkj.pojo.Attendancetype;
import com.trkj.pojo.Dept;
import com.trkj.pojo.Emp;
import com.trkj.utils.DataGrid;
import com.trkj.vo.AttendanceTypeVo;
import com.trkj.vo.AttendanceVo;
import com.trkj.vo.CheckWordDeptVo;
import com.trkj.vo.CheckWordEmpVo;
@Service
@Transactional
public class CheckWorkService {
	@Autowired
	DeptDAO deptDAO;
	@Autowired
	AttendanceDAO attendanceDAO;
	@Autowired
	AttendanceparamDAO attendanceparamDAO;
	@Autowired
	AttendancetypeDAO attendancetypeDAO;
	@Autowired
	EmpDAO empDAO;
	/**
	 * 查询所有部门和部门下的员工
	 */
	public List<CheckWordDeptVo> queryCheckDeptAndEmp() {
		List<Dept> depts = deptDAO.findAll();
		List<CheckWordDeptVo> DeptVos = new ArrayList<>();
		for (Dept dept : depts) {
			CheckWordDeptVo deptVo = new CheckWordDeptVo();
			deptVo.setDeptId(dept.getDeptId());
			deptVo.setDeptName(dept.getDeptName());
			
			if(dept.getEmps()!=null) {
				List<Emp> emps = dept.getEmps();
				List<CheckWordEmpVo> empVos = new ArrayList<>();
				for (Emp Emp : emps) {
					CheckWordEmpVo empVo = new CheckWordEmpVo();
					empVo.setEmpId(Emp.getEmpId());
					empVo.setEmpName(Emp.getEmpName());
					empVos.add(empVo);
				}
				deptVo.setEmps(empVos);
			}
			DeptVos.add(deptVo);
		}
		return DeptVos;
	}
	/**
	 * 根据员工编号查询员工的考勤记录
	 */
	public DataGrid queryCheckWorkEmpInfoByEmpId(Integer empId, Date starttime, Date endtime, Integer page, Integer rows, String sort, String order) {
		Pageable pageable = new PageRequest(page-1, rows, new Sort(Sort.Direction.fromStringOrNull(order), sort));
		if(endtime==null) {
	        Date date=new Date();  
	        Calendar calendar = Calendar.getInstance();  
	        calendar.setTime(date);  
	        calendar.add(Calendar.DAY_OF_MONTH, -30);  
	        starttime = calendar.getTime(); 
	        endtime = new Date();
		}
		Page<Attendance> pageSelect = pageSelect(empId, starttime, endtime, pageable);
		//查询结果的集合
		List<Attendance> Attendances = pageSelect.getContent();
		//转为VO集合
		List<AttendanceVo> AttendanceVos = new ArrayList<>();
		//查询考勤参数
		List<Attendanceparam> findAll = attendanceparamDAO.findAll();
		//找到启用的考勤参数
		Attendanceparam adparam = null;
		for (Attendanceparam attendanceparam : findAll) {
			if(attendanceparam.isAttparamState()) {
				adparam = attendanceparam;
			}
		}
		for (Attendance attendance : Attendances) {
			AttendanceVo attendanceVo = new AttendanceVo();
			attendanceVo.setAttendanceId(attendance.getAttendanceId());
			attendanceVo.setAttendanceDate(attendance.getAttendanceDate());
			attendanceVo.setAttendanceOffworktime(attendance.getAttendanceOffworktime()+"");
			attendanceVo.setAttendanceOnworktime(attendance.getAttendanceOnworktime()+"");
			attendanceVo.setAttypeId(attendance.getAttendancetype().getAttypeId());
			attendanceVo.setAttypeName(attendance.getAttendancetype().getAttypeName());
			attendanceVo.setEmpId(empId);
			attendanceVo.setEmpName(attendance.getEmp().getEmpName());
			
			//加入考勤参数
			attendanceVo.setAttparamId(adparam.getAttparamId());
			attendanceVo.setAttparamLate(adparam.getAttparamLate()+"");
			attendanceVo.setAttparamLeaveearly(adparam.getAttparamLeaveearly()+"");
			attendanceVo.setAttparamYearday(adparam.getAttparamYearday());
			AttendanceVos.add(attendanceVo);
		}
		return new DataGrid(pageSelect.getTotalElements(), AttendanceVos);
	}
	/**
	 * 创建分页查询
	 */
	public Page<Attendance> pageSelect(Integer empId, Date starttime, Date endtime, Pageable pageable) {
		 Page<Attendance> Attendances = attendanceDAO.findAll(new Specification<Attendance>() {
			
			@Override
			public Predicate toPredicate(Root<Attendance> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate p1=null;
				Predicate p2=null;
				/*String starttimes = starttime.toLocaleString();
				String endtimes = endtime.toLocaleString();*/
				Join<Emp, Attendance> join = root.join("emp", JoinType.LEFT);
				List<Predicate> list = new ArrayList<Predicate>();
				if (empId != null) {
					p1 = cb.equal(join.get("empId"), empId);
					list.add(p1);
				}
				if(starttime!=null) {            
					p2 = cb.between(root.get("attendanceDate"), starttime, endtime);
					list.add(p2);
				} 
				Predicate[] p = new Predicate[list.size()];
	            return cb.and(list.toArray(p));
				
			}
		},pageable);
		return Attendances;
	}
	/**
	 * 添加考勤记录
	 * @return 
	 */
	public boolean addCheckWorkRecord(String attendanceOffworktime,String attendanceOnworktime,Integer empId, Integer attypeid) {
		try {
			Attendance attendance = new Attendance();
			Attendancetype attendancetype = attendancetypeDAO.findOne(attypeid);
			Emp emp = empDAO.findOne(empId);
			attendance.setAttendancetype(attendancetype);
			attendance.setEmp(emp);
			attendance.setAttendanceDate(new Date());

	        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
	        Time btime=new Time(sdf.parse(attendanceOffworktime).getTime());
	        Time etime=new Time(sdf.parse(attendanceOnworktime).getTime());
        
			attendance.setAttendanceOffworktime(btime);
			attendance.setAttendanceOnworktime(etime);
			attendanceDAO.save(attendance);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 查询所有考勤类型
	 */
	public List<AttendanceTypeVo> queryAllAttType() {
		List<Attendancetype> Attendancetypes = attendancetypeDAO.findAll();
		List<AttendanceTypeVo> AttendanceTypeVos = new ArrayList<>();
		for (Attendancetype attendancetype : Attendancetypes) {
			AttendanceTypeVo attendanceTypeVo = new AttendanceTypeVo();
			attendanceTypeVo.setAttypeId(attendancetype.getAttypeId());
			attendanceTypeVo.setAttypeName(attendancetype.getAttypeName());
			AttendanceTypeVos.add(attendanceTypeVo);
		}
		return AttendanceTypeVos;
	}
	/**
	 * 根据员工id查询今天员工有没有考勤
	 */
	public boolean queryEmpIsCheckWorkByEmpId(Integer empid) {
		List<Object[]> objects = attendanceDAO.queryEmpIsCheckWorkByEmpId(empid);
		if(objects.size()>0) {
			return true;
		}
		return false;
	}
	
	
}
